<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="IC卡号" prop="cardNo">
        <el-input v-model="queryParams.cardNo" placeholder="请输入IC卡号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="电话" prop="tel">
        <el-input v-model="queryParams.tel" placeholder="请输入电话" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-tree-select v-model="queryParams.deptId" @keyup.enter="handleQuery" :data="deptOptions"
          :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门" check-strictly
          clearable filterable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['basic:driver:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['basic:driver:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['basic:driver:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
          v-hasPermi="['basic:driver:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['basic:driver:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="driverList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30" align="center" fixed="left" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="IC卡号" align="center" prop="cardNo" min-width="110" />
      <el-table-column label="性别" align="center" prop="gender" width="80">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" prop="tel" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_data_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center" prop="deptName" min-width="110">
        <template #default="scope">
          <el-tag type="info">{{ scope.row.deptName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['basic:driver:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['basic:driver:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改驾驶员对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="driverRef" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="IC卡号" prop="cardNo">
              <el-input v-model="form.cardNo" placeholder="请输入IC卡号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-tree-select v-model="form.deptId" :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门"
                check-strictly filterable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别">
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker clearable v-model="form.birthday" type="date" value-format="YYYY-MM-DD" placeholder="请选择生日">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idNumber">
              <el-input v-model="form.idNumber" placeholder="请输入身份证号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驾驶证号" prop="drivingLicense">
              <el-input v-model="form.drivingLicense" placeholder="请输入驾驶证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="准驾证号" prop="drivingPermitNo">
              <el-input v-model="form.drivingPermitNo" placeholder="请输入准驾证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驾驶证到期时间" prop="driverOverdue">
              <el-date-picker clearable v-model="form.driverOverdue" type="date" value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择驾驶证到期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="从业资格证" prop="certificate">
              <el-input v-model="form.certificate" placeholder="请输入从业资格证" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="auto" label="从业资格证发证机构" prop="certificateAuthority">
              <el-input v-model="form.certificateAuthority" placeholder="请输入从业资格证发证机构" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="auto" label="从业资格证到期时间" prop="certificateOverdue">
              <el-date-picker clearable v-model="form.certificateOverdue" type="date" value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择从业资格证到期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_data_status" :key="dict.value" :label="dict.value">{{ dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls"  action="#" :http-request="httpRequest"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag :data="upload.form">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <el-form :model="upload.form" ref="uploadForm" label-width="100px">
              <el-form-item label="部门" :rules="{ required: true, message: '部门不能为空', trigger: 'change' }" prop="deptId">
                <el-tree-select v-model="upload.form.deptId" :data="deptOptions"
                  :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门"
                  check-strictly filterable />
              </el-form-item>
              <div class="el-upload__tip">
                <el-checkbox v-model="upload.form.updateSupport" label="是否更新已经存在的用户数据" />
              </div>
            </el-form>
            <br />
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Driver">
import { getToken } from "@/utils/auth";
import { listDriver, getDriver, delDriver, addDriver, updateDriver } from "@/api/basic/driver";
import { deptTreeSelect } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const { sys_data_status, sys_user_sex } = proxy.useDict('sys_data_status', 'sys_user_sex');

const driverList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptName = ref("");
const deptOptions = ref([]);
/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  form: {
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    deptId: undefined,
  },
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url:  "basic/driver/import/data"
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cardNo: undefined,
    name: undefined,
    tel: undefined,
    deptId: undefined,
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    cardNo: [
      { required: true, message: "IC卡号不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    gender: [
      { required: true, message: "性别不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    deptId: [
      { required: true, message: "部门不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};

/** 查询驾驶员列表 */
function getList() {
  loading.value = true;
  listDriver(queryParams.value).then(response => {
    driverList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    cardNo: null,
    name: null,
    gender: null,
    birthday: null,
    tel: null,
    address: null,
    idNumber: null,
    drivingLicense: null,
    drivingPermitNo: null,
    drivingType: null,
    driverOverdue: null,
    certificate: null,
    certificateAuthority: null,
    certificateOverdue: null,
    status: null,
    deptId: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("driverRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加驾驶员";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getDriver(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改驾驶员";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["driverRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateDriver(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addDriver(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除驾驶员编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delDriver(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "驾驶员导入";
  upload.open = true;
};

/** 下载模板操作 */
function importTemplate() {
  proxy.download("basic/driver/import/template", {
  }, `driver_template_${new Date().getTime()}.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
function httpRequest(data) {
  // 封装FormData对象
  data.data[data.filename] = data.file
  upload.open = false;
  upload.isUploading = false;
  proxy.importFile(upload.url, data.data).then(res => {
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + res.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  }).catch(err => {
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + err + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  })
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadForm"].validate((valid) => {
    if (valid) {
      proxy.$refs["uploadRef"].submit();
    } else {
      console.log('error submit!!');
      return false;
    }
  });
};

/** 导出按钮操作 */
function handleExport() {
  proxy.download('basic/driver/export', {
    ...queryParams.value
  }, `driver_${new Date().getTime()}.xlsx`)
}

getDeptTree();

getList();
</script>
